package pt.fct.mpc.lastfm.connectivity.bt;

import pt.fct.mpc.lastfm.LastfmPreferences;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;


public class LastfmBluetoothManager
{
	private static final String TAG = "Last.fm BT Manager";

	private static LastfmBluetoothManager instance = null;
	
	@SuppressWarnings("unused")
	private Context context;
	private SharedPreferences preferences;
	
	private LastfmBluetoothGateway gateway;
	
	private LastfmBluetoothManager(Context context)
	{
		this.context = context;
		this.gateway = null;
		
		this.preferences = context.getSharedPreferences(
			LastfmPreferences.TEMPORARY_FILE_NAME, 
				Context.MODE_PRIVATE);
	}
	
	public static void initialize(Context context)
	{
		if (instance != null)
			return;
		
		instance = new LastfmBluetoothManager(context);
	}
	
	public static LastfmBluetoothManager getInstance() 
		throws LastfmBluetoothException
	{
		if (instance == null)
			throw new LastfmBluetoothException("Bluetooth Manager not initialized");
		
		return instance;
	}
	
	public void startBluetooth(LastfmBluetoothGateway gw) 
		throws LastfmBluetoothException
	{
		if (getPreferencesStatus() == false)
			throw new LastfmBluetoothException("Bluetooth not enabled");

		if (gw != null)
		{
			if (this.gateway != null)
				this.gateway.destroy();
			
			this.gateway = gw;
		}
	}
	
	public void stopBluetooth()
	{
		if (this.gateway != null)
			this.gateway.destroy();
	}
	
	public LastfmBluetoothGateway getGateway()
	{
		return this.gateway;
	}
	
	public static boolean useBluetooth()
	{
		if (instance == null)
			return false;
		else
			return (instance.getPreferencesStatus() == true);
	}

	public static boolean isOn()
	{
		return (instance != null ? instance.isStatusOn() : false);
	}

	private boolean isStatusOn()
	{
		return ((this.gateway != null) && (getPreferencesStatus() == true));
	}

	/**
	 * Acquire GWoBT status from preferences. If false, we shall not use it.
	 * @return
	 */
	private boolean getPreferencesStatus()
	{
		boolean status = this.preferences.getBoolean(
			LastfmPreferences.Temporary.PREF_BT_GW, false);
		
		Log.d(TAG, "Current BT status = "+status);
		
		return status;
	}
}
